package com.ext.aic.components;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.style.ReplacementSpan;
import android.view.View;

import com.ext.aic.databinding.AiGenerateLayoutBinding;

public class AIGenerateSpan extends ReplacementSpan {
    private Drawable mDrawable;
    private int mWidth;
    private int mHeight;

    private String content;
    private AiGenerateLayoutBinding binding;

    public AIGenerateSpan(Context context, String content, AiGenerateLayoutBinding binding) {
        this.content = content;
        this.binding = binding;
        View rootView = binding.getRoot();
        rootView.setDrawingCacheEnabled(true);
        // 测量和布局视图
        rootView.measure(
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
        );
        rootView.layout(0, 0, rootView.getMeasuredWidth(), rootView.getMeasuredHeight());
        // 生成 Bitmap
        Bitmap bitmap = Bitmap.createBitmap(
                rootView.getWidth(),
                rootView.getHeight(),
                Bitmap.Config.ARGB_8888
        );
        Canvas canvas = new Canvas(bitmap);
        rootView.draw(canvas);
        mDrawable = new BitmapDrawable(context.getResources(), bitmap);
        // 设置尺寸
        mWidth = rootView.getMeasuredWidth();
        mHeight = rootView.getMeasuredHeight();
        mDrawable.setBounds(0, 0, mWidth, mHeight);
    }

    @Override
    public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
        return mWidth;
    }

    @Override
    public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
        // 垂直居中绘制
        canvas.save();
        int transY = top + (bottom - top - mHeight) / 2;
        canvas.translate(x, transY);
        mDrawable.draw(canvas);
        canvas.restore();
    }
}
